package com.gopay.cashier.web.controller;

import java.text.DecimalFormat;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.gopay.cashier.service.impl.AntiPhishServiceImpl;
import com.gopay.common.constants.trans.PayChannel;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.gopay.cashier.common.exception.WebException;
import com.gopay.cashier.web.command.OrderInfo;
import com.gopay.cashier.web.command.PayInfoCommand;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.GatewaySource;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cust.CustCorpInfo;
import com.gopay.common.domain.rcs.RcsAntiPhishViolateLog;

/**
 * 进入收银台前的控制器
 */
@Controller
public class EntryController extends BaseController {
	protected final static Log logger = LogFactory.getLog(EntryController.class);

    @Resource(name = "antiPhishService")
    private AntiPhishServiceImpl antiPhishService;

    @RequestMapping("/pay/order.shtml")
    public ModelAndView execute(PayInfoCommand command) throws WebException {
        printRequest();
        
        String orderId = getRequest().getParameter(GOPAY_ORDER_ID);
        //CpsGenMainOrder order = getMainOrder(orderId, true);
        CpsGenMainOrder order = getMainOrder(orderId, false);
        CustCorpInfo cust = custCorpInfoService.get(order.getMerId());
        // 校验
        validate(command, order, cust);
        //关键数据
        initSecData();
        if (!(isInchargeOrder(order) || isP2PInChargeOrder(order))) {
            RcsAntiPhishViolateLog log = rcsAntiPhishingViolateLogManager.getByTransDtlSq(order.getTransDtlSq());
            if (null != log) {// 展示反钓鱼页面
                OrderInfo orderInfo = getOrderInfo(order.getGopayOrderId());
                orderInfo.setOrderAmt(new DecimalFormat("0.00").format(order.getMerTxnAmt()));
                return antiPhishPage(order, cust, log, orderInfo);
            }
        }


		//add by dongdh 20170420 直连银行加入 pay/order 与 pay/info 加入token令牌
		if (isDirectBankPay(order)) {
			if(org.apache.commons.lang.StringUtils.equals(PayChannel._01.value,order.getPayChannel()) || org.apache.commons.lang.StringUtils.equals(PayChannel._51.value,order.getPayChannel())){
				//个人网银、企业网银-直连模式
				printHeader();
				final String orderKey = getRequest().getParameter(GOPAY_ORDER_KEY);
				getRequest().getSession().setAttribute(orderId + orderKey, "0");
			}
		}

        return next(order);
    }


	private ModelAndView antiPhishPage(CpsGenMainOrder order, CustCorpInfo cust, RcsAntiPhishViolateLog log, OrderInfo orderInfo)  throws WebException{
		ModelAndView mav = new ModelAndView("00100/common/illegalIpCheck");
		mav.addObject("orderId", order.getGopayOrderId());
		mav.addObject("inc", getRequest().getParameter(FIELD_INC));
		mav.addObject("order", orderInfo);
        String[] antiInfo = antiPhishService.getAntiPhishInfo(order);
        mav.addObject("merName",antiInfo[1]);
        mav.addObject("merRefer",antiInfo[3]);
        mav.addObject("goodsInfo",antiInfo[4]);
		return mav;
	}
	
    public  ModelAndView next(CpsGenMainOrder order) throws WebException {
    	ModelAndView mav = new ModelAndView();
    	String newUrl = "/pay/info.shtml";
    	mav.addObject(GOPAY_ORDER_ID, order.getGopayOrderId());
    	mav.addObject(GOPAY_ORDER_KEY, getOrderKey(order.getGopayOrderId()));
		if(StringUtils.equals(order.getGopayIntTxnCd(), IntTxnCd._00200.value)){
			mav.addObject(CAS_GOPAY_USER, getGopayUser());
			newUrl = "/sso/login.shtml?callbackUrl=/sec/pay/info.shtml";
		}
		if(isInchargeOrder(order) || getLoginUser()!= null){
			if(isInchargeOrder(order))
                mav.addObject("inc", "y");
			newUrl = "/sec/pay/info.shtml";
		}
		/**
		 * G商融通充值，直接跳转
		 */
		if(StringUtils.equals(order.getGatewaySource(), GatewaySource.GATEWAY_SOURCE_09.toString())){
			//mav.addObject("inc", "y");
			newUrl = "/pay/info.shtml";
		}
		mav.setViewName("redirect:"+newUrl);
        return mav;
    }

	private void validate(PayInfoCommand command, CpsGenMainOrder order, CustCorpInfo cust) throws WebException {
		if (null == order) {
			logger.error("订单不存在！order not exist!" + command);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E5041);
		}
		if (null == cust) {
			logger.error("商户不存在！cust not exist!" + command);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E5001);
		}
		/*if (!"1".equals(cust.getIsRealNameCertify())) {
			logger.error("商户未通过实名认证！mer IsRealNameCertify != 1!" + order);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E2031);
		}*/
		// 只有挂起状态的订单才能继续支付
		// 如果允许08状态的订单重新发起，由于OUT_STLM_ID有值了，会误判为直连银行
		if (TxnStaCode.TXN_STA_CD_30000.value != (order.getTxnStaCd())) {
			logger.error("订单状态不对！txn_sta_cd wrong!" + order);
			throw new WebException(ProcCodeConstants.PROC_CODE_100E5042);
		}
	}

	private void initSecData(){
		HttpServletRequest request = getRequest();
		
//		String orderId = request.getParameter("orderId");
		
		request.getSession().removeAttribute(CAS_GOPAY_USER);
//        request.getSession().removeAttribute(GOPAY_ORDER_ID);
        
        if(StringUtils.isNotBlank(request.getParameter(FIELD_U))){
        	request.getSession().setAttribute(CAS_GOPAY_USER, request.getParameter(FIELD_U));
        }
//        request.getSession().setAttribute(GOPAY_ORDER_ID, orderId);
	}

}
